package com.redwine.app.chat;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.ui.EaseChatFragment;
import com.hyphenate.util.EasyUtils;
import com.redwine.app.APP;
import com.redwine.app.BaseActivity;
import com.redwine.app.MainActivity;
import com.redwine.app.R;
import com.redwine.app.net.GsonRequest;
import com.redwine.app.net.NetworkConstants;
import com.redwine.app.net.model.User;
import com.redwine.app.net.responses.BaseResponse;
import com.redwine.app.net.responses.LoginResponse;
import com.redwine.app.net.responses.SendMsgEvent;
import com.redwine.app.utils.Global;

import java.util.LinkedHashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * 聊天会话列表
 * 作者：gassion on 17/3/31 18:21
 * 最可怕的敌人，就是没有坚强的信念。
 */

public class ChatActivity extends BaseActivity {
    public static ChatActivity activityInstance;
    private EaseChatFragment chatFragment;
    String toChatUsername;
    String nickName;
    String avatarPath;
    boolean isPush;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.activity_chat);
        activityInstance = this;
        toChatUsername = getIntent().getExtras().getString(ChatConstant.EXTRA_USER_ID);
        nickName = getIntent().getExtras().getString(ChatConstant.EXTRA_USER_NICK_NAME);
        avatarPath = getIntent().getExtras().getString(ChatConstant.EXTRA_USER_AVATAR);
        isPush = getIntent().getExtras().getBoolean("isPush", false);
        chatFragment = new ChatFragment();
        requestAddData(toChatUsername);
        if (!TextUtils.isEmpty(nickName) && !TextUtils.isEmpty(avatarPath)) {
            EaseUser easeUsera = new EaseUser(toChatUsername);
            easeUsera.setAvatar(avatarPath);
            easeUsera.setNickname(nickName);
            ChatHelper.getInstance().saveContact(easeUsera);
            chatFragment.setArguments(getIntent().getExtras());
            getFragmentManager().beginTransaction().add(R.id.container, chatFragment).show(chatFragment)
                    .commitAllowingStateLoss();
        } else {
            String url = NetworkConstants.GET_USERINFO_URL;
            Map<String, String> params = new LinkedHashMap<>();
            params.put("uid", toChatUsername);
            GsonRequest<LoginResponse> request = new GsonRequest<>(url, Request.Method.POST,
                    LoginResponse.class, false, params, new Response.Listener<LoginResponse>() {
                @Override
                public void onResponse(LoginResponse response) {
                    if (response.isSuccess()) {
                        //如果登陆直接跳转到主页面
                        User responseData = response.getData();
                        EaseUser easeUsera = new EaseUser(toChatUsername);
                        easeUsera.setAvatar(responseData.getAvatar());
                        easeUsera.setNickname(responseData.getNickname());
                        ChatHelper.getInstance().saveContact(easeUsera);
                        Bundle extras = getIntent().getExtras();
                        extras.putString(ChatConstant.EXTRA_USER_NICK_NAME, responseData.getNickname());
                        chatFragment.setArguments(extras);
                        getFragmentManager().beginTransaction().add(R.id.container, chatFragment).show(chatFragment)
                                .commitAllowingStateLoss();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    finish();
                }
            });
            APP.getInstance().getRequestQueue().add(request);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        activityInstance = null;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        String username = intent.getStringExtra("userId");
        if (toChatUsername.equals(username))
            super.onNewIntent(intent);
        else {
            finish();
            startActivity(intent);
        }

    }

    @Override
    public void onBackPressed() {
        chatFragment.onBackPressed();
        if (EasyUtils.isSingleActivity(this) && isPush) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
        }
    }

    /**
     * 添加私信列表
     */
    protected void requestAddData(String private_id) {
        String url = NetworkConstants.FRIEND_ADD_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("uid", Global.user.getUid());
        params.put("friend_uid", private_id);
        GsonRequest<BaseResponse> request = new GsonRequest<>(url, Request.Method.POST,
                BaseResponse.class, false, params, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                if (response.isSuccess())
                    EventBus.getDefault().post(new SendMsgEvent(SendMsgEvent.REFURBISH_MESSAGE_DATA));
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Throwable t = error.getCause();
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }
}
